package com.lizard.schedule.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;

import com.lizard.schedule.R;
import com.lizard.schedule.ScheduleApplication;
import com.lizard.schedule.consts.FilePathConst;
import com.lizard.schedule.net.http.download.DownloadManager;
import com.lizard.schedule.service.base.BaseService;
import com.lizard.schedule.ui.activity.MainPageActivity;
import com.lizard.schedule.utils.FileUtil;
import com.lizard.schedule.utils.ToastUtil;
import com.lizard.schedule.utils.encrypt.MD5Util;

import java.io.File;

/**
 * 下载升级APK Service
 */
public class UpgradeService extends BaseService {

    public final static String PARAM_URL = "param_url";

    public final static String PARAM_VERSION_CODE = "version_code";

    private final String BROADCAST_ACTION_CANCEL = "com.lizard.schedule.upgrade.cancel";

    private final String BROADCAST_ACTION_PAUSE = "com.lizard.schedule.upgrade.pause";

    private final String BROADCAST_ACTION_CONTINUE = "com.lizard.schedule.upgrade.continue";

    /**
     * 下载使用线程数
     */
    private final int THREAD_COUNT = 2;

    private final int FOREGROUND_ID = 1;

    /**
     * 刷新通知栏的间隔进度
     */
    private final int REFRESH_PROGRESS_PERIOD = 1;

    private Notification mNotification;

    private RemoteViews mRemoteViews;

    private int mLastRefreshProgress;

    private ClickReceiver mClickReceiver;

    private String mUrl;

    private String mSaveDirPath = FilePathConst.UPGRADE_DIR.getAbsolutePath();

    private String mSaveName;

    @Override
    public void onCreate() {
        super.onCreate();
        initClickReceiver();
    }

    /**
     * 开启更新server并下载更新
     *
     * @param context
     * @param url
     */
    public static void start(Context context, String url, int versionCode){
        Intent intent = new Intent(context, UpgradeService.class);
        intent.putExtra(UpgradeService.PARAM_URL, url);
        intent.putExtra(UpgradeService.PARAM_VERSION_CODE, versionCode);
        context.startService(intent);
    }

    private void initClickReceiver(){
        mClickReceiver = new ClickReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BROADCAST_ACTION_CANCEL);
        filter.addAction(BROADCAST_ACTION_PAUSE);
        filter.addAction(BROADCAST_ACTION_CONTINUE);
        registerReceiver(mClickReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(TextUtils.isEmpty(mUrl)){
            mUrl = intent.getStringExtra(PARAM_URL);
            mSaveName = MD5Util.md5EncryptL16(mUrl) + ".apk";

            File file = new File(mSaveDirPath, mSaveName);
            if(file.exists()){ // 文件已经存在
                int versionCode = intent.getIntExtra(PARAM_VERSION_CODE, 0);
                PackageInfo packageInfo = FileUtil.getApkFilePackageInfo(this, file.getAbsolutePath());
                if(packageInfo != null && packageInfo.packageName.equals(ScheduleApplication.PACKAGE_NAME) && packageInfo.versionCode == versionCode){ // 包名和版本号相同
                    installApk();
                    stopSelf();
                    return super.onStartCommand(intent, flags, startId);
                }
            }

            download();
        } else{
            ToastUtil.showScheduleToastS(R.string.download_exist);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 开始下载
     */
    private void download() {

        if (!FileUtil.isSdCardExist()) {
            ToastUtil.showScheduleToastS(R.string.no_sd_card);
            stopSelf();
            return;
        }

        DownloadManager.getInstance().download(mUrl,
                THREAD_COUNT,
                mSaveDirPath,
                mSaveName,
                new DownloadManager.DownloadListener() {

                    @Override
                    public void error() {
                        ToastUtil.showScheduleToastS(R.string.download_error);
                        UpgradeService.this.stopSelf();
                    }

                    @Override
                    public void exist() {
                        ToastUtil.showScheduleToastS(R.string.download_exist);
                    }

                    @Override
                    public void waiting() {
                        mLastRefreshProgress = -10;
                        initNotification();
                        startForeground(FOREGROUND_ID, mNotification);
                    }

                    @Override
                    public void begin(double percent, boolean supportRanges) {
                        int progress = (int) (percent * 100);
                        setProgressTxt(progress);
                        if(supportRanges){ // 支持断点下载才显示暂停按钮
                            mRemoteViews.setViewVisibility(R.id.pause_btn, View.VISIBLE);
                        }
                        startForeground(FOREGROUND_ID, mNotification);
                    }

                    @Override
                    public void pause(double percent) {
                        mRemoteViews.setTextViewText(R.id.content_txt, getString(R.string.pause_download) + (int) (percent * 100) + "%");
                        setContinueBtnClick();
                        startForeground(FOREGROUND_ID, mNotification);
                    }

                    @Override
                    public void stop() {
                        UpgradeService.this.stopSelf();
                    }

                    @Override
                    public void finish() {
                        // 下载结束直接运行安装
                        installApk();
                        UpgradeService.this.stopSelf();
                    }

                    @Override
                    public void progress(double percent) {
                        refreshNotificationProgress(percent);
                    }
                });

    }

    /**
     * 暂停下载
     */
    private void pause() {
        DownloadManager.getInstance().pause(mUrl, mSaveDirPath, mSaveName);
    }

    /**
     * 继续下载
     */
    private void continueDownload() {
        download();
    }

    /**
     * 取消下载
     */
    private void cancel() {
        DownloadManager.getInstance().stop(mUrl, mSaveDirPath, mSaveName);
        stopSelf();
    }

    /**
     * 安装应用
     */
    private void installApk() {
        Uri uri = Uri.fromFile(new File(mSaveDirPath, mSaveName));
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 初始化通知栏
     */
    private void initNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.icon_notification);
        builder.setTicker(getString(R.string.begin_download_upgrade));
        mRemoteViews = new RemoteViews(getPackageName(), R.layout.upgrade_notification_content);
        mRemoteViews.setTextViewText(R.id.content_txt, getString(R.string.waiting_download));
        mRemoteViews.setViewVisibility(R.id.pause_btn, View.GONE);
        builder.setContent(mRemoteViews);
        Intent intent = new Intent(this, MainPageActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);
        mNotification = builder.build();
        setCancelBtnClick();
        setPauseBtnClick();
    }

    private void setCancelBtnClick() {
        Intent intent = new Intent(BROADCAST_ACTION_CANCEL);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.cancel_btn, pendingIntent);
    }

    private void setPauseBtnClick() {
        mRemoteViews.setTextViewText(R.id.pause, getString(R.string.pause));
        Intent intent = new Intent(BROADCAST_ACTION_PAUSE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.pause_btn, pendingIntent);
    }

    private void setContinueBtnClick() {
        mRemoteViews.setTextViewText(R.id.pause, getString(R.string.continue_download));
        Intent intent = new Intent(BROADCAST_ACTION_CONTINUE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.pause_btn, pendingIntent);
    }

    /**
     * 刷新通知栏
     *
     * @param percent
     */
    private void refreshNotificationProgress(double percent) {
        int progress = (int) (percent * 100);
        if (progress - mLastRefreshProgress >= REFRESH_PROGRESS_PERIOD || progress >= 100) {
            mLastRefreshProgress = progress;
            setProgressTxt(progress);
            mNotification.contentView = mRemoteViews;
            startForeground(FOREGROUND_ID, mNotification);
        }
    }

    /**
     * 进度信息文案设置
     *
     * @param progress
     */
    private void setProgressTxt(int progress) {
        mRemoteViews.setTextViewText(R.id.content_txt, getString(R.string.downloading) + progress + "%");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
        unregisterReceiver(mClickReceiver);
    }

    /**
     * 按钮点击通过广播传递进来
     */
    class ClickReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (BROADCAST_ACTION_CANCEL.equals(intent.getAction())) {
                cancel();
            } else if (BROADCAST_ACTION_PAUSE.equals(intent.getAction())) {
                pause();
            } else if (BROADCAST_ACTION_CONTINUE.equals(intent.getAction())) {
                continueDownload();
            }
        }
    }
}
